const {
  TaskProxy,
  PushProxy
} = require('../proxys')


module.exports = class TaskController {

  static async createTask (ctx) {
    let { taskInfo } = ctx.request.body
    let index = 1
    if (Object.prototype.toString.call(taskInfo) !== '[object Object]') {
      ctx.status = 400
      ctx.body = {
        code: -1,
        msg: '参数错误'
      }
    }
    const latestTask = await TaskProxy.findLatestTask()
    if (latestTask) {
      index = latestTask.index + 1
    }
    taskInfo.index = index
    taskInfo.time = Date.now()
    taskInfo.status = '等待推送'
    await TaskProxy.newAndSave(taskInfo)
    ctx.body = {
      code: 0,
      msg: '任务队列添加成功'
    }
  }

  static async getTaskList (ctx) {
    let { page = 1, size = 20 } = ctx.query
    page = parseInt(page)
    size = parseInt(size)
    if (isNaN(page) || isNaN(size)) {
      ctx.status = 400
      ctx.body = {
        code: -1,
        msg: '参数错误'
      }
    }
    const result = await TaskProxy.getTaskList(page, size)
    ctx.body = {
      code: 0,
      data: result
    }
  }

  static async deleteTask (ctx) {
    const { id } = ctx.params
    const task = TaskProxy.findOne({ _id: id })
    if (!task) {
      ctx.status = 400
      ctx.body = {
        code: -1,
        msg: '参数错误'
      }
    }
    await TaskProxy.deleteById(id)
    ctx.body = {
      code: 0,
      msg: '删除成功'
    }
  }

  static async updateTask (ctx) {
    const { id } = ctx.params
    const task = await TaskProxy.findOne({ _id: id })
    const nextTask = await TaskProxy.findNextTask()
    if (!task) {
      ctx.status = 400
      ctx.body = {
        code: -1,
        msg: '参数错误'
      }
    }
    let index = 0
    if (nextTask) {
      index = nextTask.index - 1
    }
    await TaskProxy.updateTaskById(id, { index })
    ctx.body = {
      code: 0,
      msg: '更新成功'
    }
  }
}
